<?php

namespace App\Http\Middleware;

use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\WaiMai\Channel\BaseWaiMai;
use App\Kuafu\WaiMai\Model\WaiMaiCallbackLogModel;
use App\Kuafu\WaiMai\Model\WaiMaiOrderIdShopIdMappingModel;
use App\Kuafu\WaiMai\Service\BaseWaiMaiOrderService;
use App\Kuafu\WaiMai\Service\WaiMaiShopService;
use Closure;
use Illuminate\Support\Facades\Log;

class MtWaiMaiCheckSign
{
    private $sourceType = CodeEnum::SOURCE_TYPE_MT;

    /**
     * 美团外卖回调接口 - 日志、校验签名
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // 日志入库
        $orderId     = (int)$request->get('order_id', 0);
        $thirdShopId = (string)$request->get('wm_poi_id', '');
        $route       = $request->getPathInfo();
        list($shopId, $thirdShopId) = $this->getShopId($thirdShopId, $orderId);

        // 请求数据为空的，直接返回
        if (!$request->all()) {
            return response()->json(['data' => 'ok'])->header('Content-Type', 'application/json;charset=utf-8');
        }

        BaseWaiMaiOrderService::$callBackShopId = $shopId;
        BaseWaiMaiOrderService::$callBackId     = WaiMaiCallbackLogModel::addData($this->sourceType, $orderId,
            (string)$thirdShopId, json_encode($request->all()), $route, $shopId);

        // 验签
//        $check = (new MtWaiMai(0))->checkSign($request, $request->all());
//        if (!$check) {
//            SendFs::newRobot()->setTitleContent('美团外卖回调接口验签失败', json_encode($request->all()))->send();
//            return (new BaseController($request))->fail(1, '验签失败');
//        }

        return $next($request);
    }

    private function getShopId(string $thirdShopId, int $orderId): array
    {
        if ($thirdShopId) {
            return [WaiMaiShopService::getThirdMappingCache($thirdShopId, $this->sourceType), $thirdShopId];
        }

        if ($orderId) {

            $shopId = WaiMaiOrderIdShopIdMappingModel::getShopId($orderId);
            if ($shopId) {
                return [$shopId, optional(WaiMaiShopService::getMappingCache($shopId, $this->sourceType))->thirdShopId];
            }

            Log::channel('waiMai')->info("MT ORDER LOST: {$orderId}");

            $order = BaseWaiMai::getIns($this->sourceType, 0)->getOrderDetail($orderId);
            if (!$order['status']) {
                return [0, ''];
            }

            $shopId = ['data']['shopId'] ?? 0;
            if ($shopId) {
                WaiMaiOrderIdShopIdMappingModel::addData($orderId, $shopId, $this->sourceType);
            }

            return [$shopId, optional(WaiMaiShopService::getMappingCache($shopId, $this->sourceType))->thirdShopId];
        }

        Log::channel('waiMai')->info("MtWaiMaiCheckSign Param Sudden:", request()->all());
        return [0, ''];
    }
}
